<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.supplierName" placeholder="供应商名称" style="width: 200px;" class="filter-item" @keyup.enter.native="btnQuery" />
      <el-dropdown split-button type="primary" class="filter-item" @click="btnQuery">
        <i class="el-icon-search el-icon--left" />查询
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item icon="el-icon-zoom-out" @click.native="btnReset">重置</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button-group>
        <el-button v-permission="'purchase:supplier:save'" icon="el-icon-plus" type="primary" class="filter-item" @click="btnCreate">新增</el-button>
        <el-button v-permission="'purchase:supplier:delete'" icon="el-icon-delete" class="filter-item" @click="btnDelete()">批量删除</el-button>
        <el-button v-permission="'purchase:supplier:delete'" type="warning" class="filter-item" @click="btnReplace()">批量替换</el-button>
      </el-button-group>
    </div>
    <el-table
      ref="multipleTable"
      :data="records"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :cell-style="{padding:'3px'}"
      @selection-change="selectionChange"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column label="供应商名称" prop="supplierName" align="center"><template slot-scope="scope"><span>{{ scope.row.supplierName }}</span></template></el-table-column>
      <el-table-column label="联系人" prop="contactPerson" width="80px" align="center"><template slot-scope="scope"><span>{{ scope.row.contactPerson }}</span></template></el-table-column>
      <el-table-column label="联系电话" prop="contactPhone" width="110px" align="center"><template slot-scope="scope"><span>{{ scope.row.contactPhone }}</span></template></el-table-column>
      <el-table-column label="账户银行" prop="bankName" align="center"><template slot-scope="scope"><span>{{ scope.row.bankName }}</span></template></el-table-column>
      <el-table-column label="账户号" prop="bankAccount" align="center"><template slot-scope="scope"><span>{{ scope.row.bankAccount }}</span></template></el-table-column>
      <el-table-column label="备注" prop="comment" width="80px" align="center"><template slot-scope="scope"><span>{{ scope.row.comment }}</span></template></el-table-column>
      <el-table-column label="操作" align="center" width="160px">
        <template slot-scope="{row}">
          <el-button-group style="float: left;">
            <el-button type="text" @click.native="btnView(row)">查看</el-button>
            <el-button v-permission="'purchase:supplier:update'" style="margin-left: 5px" type="text" divided @click.native="btnUpdate(row)">修改</el-button>
            <el-button v-permission="'purchase:file:list'" style="margin-left: 5px" type="text" divided @click.native="btnFileView(row.id)">附件</el-button>
            <el-button v-permission="'purchase:order:delete'" style="margin-left: 5px" type="text" divided @click.native="btnDelete(row.id)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :current.sync="listQuery.current"
      :size.sync="listQuery.size"
      @pagination="list"
    />

    <el-dialog title="" :visible.sync="dialogUpdateFormVisible" width="50%" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="110px">
        <el-form-item label="供应商名称" prop="supplierName"><el-input v-model="temp.supplierName" /></el-form-item>
        <el-form-item label="联系人" prop="contactPerson"><el-input v-model="temp.contactPerson" /></el-form-item>
        <el-form-item label="联系电话" prop="contactPhone"><el-input v-model="temp.contactPhone" /></el-form-item>
        <el-form-item label="账户银行" prop="bankName"><el-input v-model="temp.bankName" /></el-form-item>
        <el-form-item label="账户" prop="bankAccount"><el-input v-model="temp.bankAccount" /></el-form-item>
        <el-form-item label="备注" prop="comment"><el-input v-model="temp.comment" /></el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="dialogUpdateFormVisible = false">取消</el-button>
        <el-button icon="el-icon-check" type="primary" @click="dialogStatus=='update'?updateData():createData()">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="" :visible.sync="dialogFormVisible" width="90%" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="temp" :disabled="dialogStatus==='view'" label-position="right" label-width="110px">
        <!-- <el-form-item label="ID" prop="id"><el-input v-model="temp.id" :readonly="dialogStatus==='update'"/></el-form-item> -->
        <el-col :span="12">
          <el-form-item label="供应商名称" prop="supplierName"><el-input v-model="temp.supplierName" /></el-form-item>
        </el-col>
        <!--<el-form-item label="联系人" prop="supplierName"><el-input v-model="temp.contactPerson" /></el-form-item>-->
        <!--<el-form-item label="联系电话" prop="supplierName"><el-input v-model="temp.contactPhone" /></el-form-item>-->
        <el-col :span="12">
          <el-form-item label="备注" prop="comment"><el-input v-model="temp.comment" /></el-form-item>
        </el-col>
      </el-form>
      <div class="filter-container">
        <el-input v-model="listOrderQuery.invoice" placeholder="发票号" style="width: 200px;" class="filter-item" @keyup.enter.native="btnQueryOrderDetail"/>
        <el-date-picker v-model="listOrderQuery.startDate" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="审批单开始日期" style="width: 200px;" class="filter-item" @keyup.enter.native="btnQueryOrderDetail" />
        <el-date-picker v-model="listOrderQuery.endDate" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="审批单结束日期" style="width: 200px;" class="filter-item" @keyup.enter.native="btnQueryOrderDetail" />
        <el-select v-model="listOrderQuery.contractFinished" clearable placeholder="合同完成状态">
          <el-option
            v-for="item in contractStateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-button split-button type="primary" class="filter-item" @click="btnQueryOrderDetail">
          <i class="el-icon-search el-icon--left" />查询
        </el-button>
        <el-button split-button type="primary" class="filter-item" @click="btnExport">
          <i class="el-icon-download el-icon--left" />导出查询结果
        </el-button>
      </div>
      <el-table
        ref="detailTable"
        show-summary
        :summary-method="getSummaries"
        :data="orderDetail"
        :span-method="arraySpanMethod"
        border
        style="width: 100%"
      >
        <el-table-column prop="orderCode" label="审批单编号" align="center" width="80px" />
        <el-table-column prop="orderDate" label="审批单日期" align="center" />
        <el-table-column prop="projectName" label="项目（用途）" align="center" />
        <el-table-column prop="indentCode" label="订单编号" align="center" width="100px" />
        <!--<el-table-column prop="contractCode" label="合同编号" align="center" width="100px" />-->
        <el-table-column label="合同编号" align="center" width="100px">
          <template slot-scope="{row}">
            <span>{{ row.contractCode }}</span>
            <el-button v-if="!isEmpty(row.contractCode)" type="text" @click.native="editContract(row)">编辑</el-button>
            <el-button v-else type="text" @click.native="btnGen(row)">合并订单</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="contractState" label="合同状态" align="center" />
        <el-table-column prop="aogSituation" label="到货情况" align="center" />
        <!--<el-table-column prop="invoice" label="发票" align="center" />-->
        <el-table-column label="发票" align="center" width="100px">
          <template slot-scope="{row}">
            <span>{{ row.invoice }}</span>
            <el-button v-if="!isEmpty(row.invoice)" type="text" @click.native="exportInvoicePayment(row)">导出付款单</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="paymentSituation" label="付款情况" align="center">
          <template slot-scope="scope">
            <span style="white-space:pre-line">{{ scope.row.paymentSituation }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="contractSubAmount" label="合同小计" align="center" />
        <el-table-column prop="materialName" label="设备名称" align="center" width="150px" />
        <el-table-column prop="materialSpecification" label="规格" align="center" width="100px" />
        <el-table-column prop="unitPrice" label="设备单价" align="center" width="50px" />
        <el-table-column prop="materialNum" label="采购数量" align="center" width="50px" />
        <el-table-column prop="materialTotalPrice" label="总价（元）" align="center" width="100px" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus!=='view'" icon="el-icon-check" type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
    <contract-detail ref="contractDetailRef" :dialog-status="'update'" @handleChild="handleChild" />
    <el-dialog
      title="提示"
      :visible.sync="confirmDialogVisible"
      width="30%"
    >
      <span>确定删除</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="confirmDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doDelete()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="替换供应商" width="20%" :visible.sync="replaceDialogVisible">
      <label>目标供应商 </label>
      <el-select v-model="nReplaceId" filterable placeholder="请选择">
        <el-option
          v-for="item in supplierOptions"
          :key="item.id"
          :label="item.supplierName"
          :value="item.id"
        />
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="replaceDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doReplace()">确 定</el-button>
      </span>
    </el-dialog>

    <!--合并采购订单-->
    <gen-contract ref="genContractRef" @handleChild="handleChild" />
    <el-dialog
      ref="dialogRef"
      custom-class="selfDialog"
      :visible.sync="fileDialogVisible"
      width="80%"
      title="附件"
    >
      <file-list ref="supplierFiles" :query-file-param="queryFileTemp" />
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { getAction, putAction, postAction, deleteAction, getFileAction } from '@/api/manage'
import { Message } from 'element-ui'
import contractDetail from '@/views/purchase/contract/contractDetail'
import genContract from '@/views/purchase/contract/genContract'
import fileList from '@/views/purchase/file/components/fileList'

export default {
  name: 'PurchaseSupplier',
  components: {
    Pagination,
    contractDetail,
    genContract,
    fileList
  },
  data() {
    return {
      contractStateOptions: [{
        value: false,
        label: '未完成'
      }, {
        value: true,
        label: '已完成'
      }
      ],
      orderCodeArr: [],
      projectNameArr: [],
      indentCodeArr: [],
      contractCodeArr: [],
      dicts: [],
      records: null,
      selectedRecords: [],
      total: 0,
      listQuery: {
        current: 1,
        size: 10,
        supplierName: undefined
      },
      listOrderQuery: {
        invoice: undefined,
        supplierId: undefined,
        startDate: undefined,
        endDate: undefined,
        contractFinished: undefined
      },
      dialogFormVisible: false,
      fileDialogVisible: false,
      queryFileTemp: {
        supplierId: ''
      },
      dialogUpdateFormVisible: false,
      confirmDialogVisible: false,
      replaceDialogVisible: false,
      dialogStatus: '',
      temp: {
        id: undefined,
        supplierName: '',
        contactPerson: '',
        contactPhone: '',
        bankName: '',
        bankAccount: '',
        comment: ''
      },
      orderDetail: [],
      rules: {
        id: [{ required: true, message: '该项不能为空', trigger: 'change' }],
        supplierName: [{ required: true, message: '该项不能为空', trigger: 'change' }]
      },
      deleteIds: [],
      replaceIds: [],
      supplierOptions: [],
      nReplaceId: null
    }
  },
  beforeCreate() {

  },
  created() {
    this.list()
  },
  methods: {
    btnGen(row) {
      this.$refs.genContractRef.show(row.orderId, row.supplierId, true)
    },
    handleChild(data) {
      const fns = {
        contractUpdated() {
          this.listOrder()
        },
        indentMerged() {
          this.listOrder()
        }
      }
      return fns[data.type] && fns[data.type].call(this)
    },
    editContract(row) {
      this.$refs.contractDetailRef.show(row.contractId)
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (column.property !== 'materialTotalPrice') {
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          // sums[index] += ' 元'
        }
      })

      return sums
    },

    listOrder() {
      getAction('/purchase/orderDetail/listBy', this.listOrderQuery).then(res => {
        const { data } = res
        this.orderDetail = data
        this.merage()
        this.$nextTick(() => {
          this.orderDetail = data
          // this.$refs['detailTable'].setData(data)
        })
      })
    },
    list() {
      getAction('/purchase/supplier/list', this.listQuery).then(res => {
        const { data } = res
        this.records = data.records
        this.total = data.total
      })
    },
    btnQuery() {
      this.listQuery.current = 1
      this.list()
    },
    btnQueryOrderDetail() {
      this.listOrder()
    },
    btnReset() {
      this.listQuery = {
        current: 1,
        size: 10,
        supplierName: undefined
      }
      this.list()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        supplierName: '',
        contactPerson: '',
        contactPhone: '',
        bankName: '',
        bankAccount: '',
        comment: ''
      }
    },
    btnExport() {
      getFileAction('/purchase/supplier/export', this.listOrderQuery).then(res => {
        if (res.type === 'application/json') {
          const reader = new FileReader() // 创建读取文件对象
          reader.addEventListener('loadend', function() { //
            const resJson = JSON.parse(reader.result) // 返回的数据
            Message.error(resJson.msg)
          })
          reader.readAsText(res, 'utf-8') // 设置读取的数据以及返回的数据类型为utf-8
        } else {
          const doca = window.document.createElement('a')
          const url = window.URL.createObjectURL(res)

          doca.href = url
          doca.setAttribute('download', this.temp.supplierName + '.xls')
          window.document.body.appendChild(doca)
          doca.click()
          window.document.body.removeChild(doca)
          window.URL.revokeObjectURL(url)
        }
      })
    },
    btnView(row) {
      this.dialogStatus = 'view'
      this.temp = Object.assign({}, row)
      // 查询detail
      const start = this.nearlyYear()
      this.listOrderQuery = { supplierId: row.id, startDate: start, endDate: undefined, contractFinished: undefined }
      getAction('/purchase/orderDetail/listBy', this.listOrderQuery).then(res => {
        const {
          data
        } = res
        this.orderDetail = data
        this.merage()
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    btnCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogUpdateFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          postAction('/purchase/supplier/save', this.temp).then(({ msg }) => {
            this.dialogUpdateFormVisible = false
            Message.success(msg)
            this.list()
          })
        }
      })
    },
    btnUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogUpdateFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          putAction('/purchase/supplier/update', this.temp).then(({ msg }) => {
            this.dialogUpdateFormVisible = false
            Message.success(msg)
            this.list()
          })
        }
      })
    },
    doDelete() {
      deleteAction('/purchase/supplier/delete', {
        ids: this.deleteIds.toString()
      }).then(({ msg }) => {
        Message.success(msg)
        this.list()
      })
      this.confirmDialogVisible = false
    },
    btnReplace() {
      const oids = this.selectedRecords.map(record => {
        return record.id
      })
      if (oids.length === 0) {
        Message.error('请选择要替换的记录')
        return
      }
      this.replaceIds = oids

      getAction('/purchase/supplier/listAll').then(
        res => {
          const { data } = res
          this.supplierOptions = data.filter((item) => {
            return !this.replaceIds.includes(item.id)
          })
        }
      )

      this.replaceDialogVisible = true
    },
    doReplace() {
      getAction('/purchase/supplier/replaceSupplier', {
        oids: this.replaceIds.toString(), nid: this.nReplaceId
      }).then(({ msg }) => {
        Message.success(msg)
        this.list()
      })
      this.nReplaceId = null
      this.replaceDialogVisible = false
    },
    btnDelete(id) {
      const ids = id ? [id] : this.selectedRecords.map(record => {
        return record.id
      })
      if (ids.length === 0) {
        Message.error('请选择要删除的记录')
        return
      }
      this.deleteIds = ids
      this.confirmDialogVisible = true
    },
    selectionChange(selectedRecords) {
      this.selectedRecords = selectedRecords
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0 || columnIndex === 1) {
        const row1 = this.orderCodeArr[rowIndex]
        const col1 = row1 > 0 ? 1 : 0
        return {
          rowspan: row1,
          colspan: col1
        }
      }
      if (columnIndex === 2) {
        const row1 = this.projectNameArr[rowIndex]
        const col1 = row1 > 0 ? 1 : 0
        return {
          rowspan: row1,
          colspan: col1
        }
      }

      if (columnIndex === 3) {
        const row1 = this.indentCodeArr[rowIndex]
        const col1 = row1 > 0 ? 1 : 0
        return {
          rowspan: row1,
          colspan: col1
        }
      }
      if (columnIndex === 8 || columnIndex === 4 || columnIndex === 5 || columnIndex === 6 || columnIndex === 7 || columnIndex === 9) {
        const row1 = this.contractCodeArr[rowIndex]
        const col1 = row1 > 0 ? 1 : 0
        return {
          rowspan: row1,
          colspan: col1
        }
      }
    },
    nearlyYear() {
      let start = ''
      const now = new Date()
      if (now.getMonth() === 11) {
        start = now.getFullYear() + '-01-01'
      } else {
        start = (now.getFullYear() - 1) + '-' + (now.getMonth() < 8 ? '0' + (now.getMonth() + 2) : (now.getMonth() + 2)) + '-01'
      }
      return start
    },
    btnFileView(supplierId) {
      this.queryFileTemp.supplierId = supplierId
      this.fileDialogVisible = true
      if (this.$refs.supplierFiles !== undefined) {
        this.$refs.supplierFiles.getlistFile()
      }
    },
    exportInvoicePayment(row) {
      var param = { contractId: row.contractId, exWithInvoice: true }
      getFileAction('/purchase/contract/exportPayment', param).then(res => {
        if (res.type === 'application/json') {
          const reader = new FileReader() // 创建读取文件对象
          reader.addEventListener('loadend', function() { //
            const resJson = JSON.parse(reader.result) // 返回的数据
            Message.error(resJson.msg)
          })
          reader.readAsText(res, 'utf-8') // 设置读取的数据以及返回的数据类型为utf-8
        } else {
          const doca = window.document.createElement('a')
          const url = window.URL.createObjectURL(res)

          doca.href = url
          doca.setAttribute('download', row.invoice + '.xls')
          window.document.body.appendChild(doca)
          doca.click()
          window.document.body.removeChild(doca)
          window.URL.revokeObjectURL(url)
        }
      })
    },
    merage() {
      this.orderCodeArr = []
      this.projectNameArr = []
      this.contractCodeArr = []
      this.indentCodeArr = []

      let orderPos = 0
      let contractPos = 0
      let supplierPos = 0
      let indentPos = 0
      for (let i = 0; i < this.orderDetail.length; i++) {
        if (i === 0) {
          this.orderCodeArr.push(1)
          this.projectNameArr.push(1)
          this.contractCodeArr.push(1)
          this.indentCodeArr.push(1)
        } else {
          if (this.orderDetail[i].orderCode === this.orderDetail[i - 1].orderCode) {
            this.orderCodeArr[orderPos] += 1
            this.orderCodeArr.push(0)
          } else {
            this.orderCodeArr.push(1)
            orderPos = i
          }
          if (this.orderDetail[i].projectName === this.orderDetail[i - 1].projectName) {
            this.projectNameArr[supplierPos] += 1
            this.projectNameArr.push(0)
          } else {
            this.projectNameArr.push(1)
            supplierPos = i
          }

          if (this.orderDetail[i].contractCode === this.orderDetail[i - 1].contractCode) {
            this.contractCodeArr[contractPos] += 1
            this.contractCodeArr.push(0)
          } else {
            this.contractCodeArr.push(1)
            contractPos = i
          }

          if (this.orderDetail[i].indentCode === this.orderDetail[i - 1].indentCode) {
            this.indentCodeArr[indentPos] += 1
            this.indentCodeArr.push(0)
          } else {
            this.indentCodeArr.push(1)
            indentPos = i
          }
        }
      }
    }
  }
}
</script>
